package cn.lijiajia3515.cairo.auth.modules.account;

import cn.lijiajia3515.cairo.auth.domain.mongo.AccountMongo;
import cn.lijiajia3515.cairo.auth.modules.department.PathDepartment;
import cn.lijiajia3515.cairo.auth.modules.role.Role;
import cn.lijiajia3515.cairo.common.BaseConverter;

import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class AccountConverter extends BaseConverter {

	public static Account convert(String appId,
								  AccountMongo m, Map<String, Role> roleMap,
								  Map<String, PathDepartment> departmentMap,
								  Map<String, Account> accountMap,
								  AccountExtension extension) {

		Account.AccountBuilder<?,?> builder = Account.builder().id(m.getId());
		if (extension.fields().contains(AccountField.NAME)) builder.nickname(m.getName());
		if (extension.fields().contains(AccountField.USERNAME)) builder.login(m.getUsername());
		if (extension.fields().contains(AccountField.PHONE_NUMBER)) builder.phoneNumber(m.getPhoneNumber());
		if (extension.fields().contains(AccountField.EMAIL)) builder.email(m.getEmail());
		if (extension.fields().contains(AccountField.AVATAR_URL)) builder.avatarUrl(m.getAvatarUrl());
		if (extension.fields().contains(AccountField.ROLE))
			builder.roles(Optional.ofNullable(m.getRole().getOrDefault(appId, Collections.emptySet())).orElse(Collections.emptySet()).stream().map(x -> roleMap.getOrDefault(x, Role.builder().id(x).name(x).build())).collect(Collectors.toList()));
		if (extension.fields().contains(AccountField.DEPARTMENT))
			builder.departments(Optional.ofNullable(m.getDepartment().getOrDefault(appId, Collections.emptySet())).orElse(Collections.emptySet()).stream().map(x -> departmentMap.getOrDefault(x, PathDepartment.builder().ids(Collections.singletonList(x)).names(Collections.singletonList(x)).remarks(Collections.singletonList("哈哈哈")).build())).collect(Collectors.toList()));
		if (extension.fields().contains(AccountField.ACCOUNT))
			builder.accountEnabled(m.getAccountEnabled()).accountLocked(m.getAccountLocked());
		if (extension.fields().contains(AccountField.LAST_LOGIN_AT)) builder.lastLoginAt(m.getLastLoginAt());
		if (extension.fields().contains(AccountField.META))
			builder.meta(convert(m.getMeta(), accountMap));
		return builder.build();
	}
}
